﻿using System;
using System.Diagnostics.Contracts;
using System.Windows.Input;

namespace Sundstrom.Mvvm.Command 
{
    /// <summary>
    /// Relay command. 
    /// Source: http://wpftutorial.net/DelegateCommand.html
    /// </summary>
	public class RelayCommand : ICommand
	{
		private readonly Func<bool> _canExecute;
		private readonly Action _execute;

		public event EventHandler CanExecuteChanged;

		public RelayCommand(Action execute) 
		{
            Contract.Requires<ArgumentNullException>(execute != null);

            _execute = execute;
            _canExecute = null;
		}

		public RelayCommand(Action execute, 
		                       Func<bool> canExecute)
		{
            Contract.Requires<ArgumentNullException>(execute != null);
            Contract.Requires<ArgumentNullException>(canExecute != null);

			_execute = execute;
			_canExecute = canExecute;
		}

		public bool CanExecute(object parameter)
		{
			if (_canExecute == null)
			{
				return true;
			}

			return _canExecute();
		}

		public void Execute(object parameter)
		{
			_execute();
		}

		public void RaiseCanExecuteChanged()
		{
            if (CanExecuteChanged != null)
                CanExecuteChanged(this, EventArgs.Empty);
		}
	}
}